package com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.activity.adapter.PersonAdapter;
import com.activity.adapter.PersonAdapter1;
import com.activity.bean.CategoryBean;
import com.activity.bean.OpusBean;
import com.activity.bean.UserBean;
import com.api.param.AddWorkParam;
import com.api.param.CommentParam;
import com.api.param.PageParam;
import com.api.param.UpdateUserParam;
import com.api.param.UserParam;
import com.api.viewModel.LoginVM;
import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.donkingliang.groupedadapter.layoutmanger.GroupedGridLayoutManager;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.widget.BLinearLayout;
import com.example.apple.ddhr_new.activity.widget.PictureEditView;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ImageViewUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.example.lzbase.BaseViewModelActivity;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import event.MessageEvent;

import static androidx.recyclerview.widget.StaggeredGridLayoutManager.GAP_HANDLING_NONE;

public class Person1Activity extends BaseViewModelActivity<LoginVM> {
    PageParam pageParam = new PageParam();

    private String imgurl;

    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.btn_reload)
    Button btnReload;
    @BindView(R.id.l_empty)
    LinearLayout lEmpty;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.nav_bar)
    LinearLayout lNav;
    private PersonAdapter1 personalAdapter;
    private int mOffset;
    private int mScrollY;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private ArrayList<CategoryBean> categorys;
    private int selectIndex;

    @Override
    protected int titleText() {
        return R.string.app_name;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person1;
    }

    @Override
    public void initStatusBar() {
        ImmersionBar.with(this)
                .transparentStatusBar()
                .init();
//        <com.scwang.smartrefresh.layout.footer.ClassicsFooter
//
//
//        android:paddingLeft="15dp"
//        android:gravity="center"
//        app:srlTextLoading=""
//        app:srlTextFinish=""
//        app:srlTextRefreshing=""
//        android:layout_width="match_parent"
//        android:layout_height="match_parent"/>
    }


    public void updateIcon(){
        if(StringUtils.isEmpty(App.getInstance().getAccount().getUserbackground()) ){

//            parallax.setImageResource(R.drawable.iconbg);
        }else
        {
//            ImageViewUtil.loadImage(App.getInstance().getAccount().getUserbackground(),parallax,this,R.drawable.iconbg);
        }
        tvTitle.setText(App.getInstance().getAccount().getUsernickname());
        personalAdapter.notifyDataChanged();
    }
    @Override
    protected void created(@Nullable Bundle savedInstanceState) {
        super.created(savedInstanceState);





        personalAdapter = new PersonAdapter1(this);

//       recycleView.setPadding(ScreenUtil.dp2px(this,0),ScreenUtil.dp2px(this,10),ScreenUtil.dp2px(this,0),0);

        recycleView.setAdapter(personalAdapter);
        lNav.getBackground().setAlpha(0);
        tvTitle.setVisibility(View.INVISIBLE);
        lNav.setPadding(0,ImmersionBar.getStatusBarHeight(this),0,0);
        recycleView.addItemDecoration(new PictureEditView.SquareLayoutItemDecoration(ScreenUtil.dp2px(this,0),ScreenUtil.dp2px(this,0),2));

         staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(GAP_HANDLING_NONE);
        recycleView.setItemAnimator(null);
        GroupedGridLayoutManager gridLayoutManager =  new GroupedGridLayoutManager(this, 2, personalAdapter);
        recycleView.setLayoutManager(staggeredGridLayoutManager);



        refreshLayout.setEnableAutoLoadMore(false);


        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                headerFreshing();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                footerFreshing();

            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                int bz = 0;
//                if (Math.abs(mOffset) > ScreenUtil.dp2px(Person1Activity.this, 50)) {
//                    bz = ScreenUtil.dp2px(Person1Activity.this, 50);
//                } else {
//                    bz = Math.abs(mOffset);
//                }
//                float p = 1 - ((float) bz / (float) ScreenUtil.dp2px(Person1Activity.this, 50));
//
//                Log.e("sadasdasdasd", p + "");
//
//                if (recycleView.getChildAt(0).findViewById(R.id.l_bz) != null) {
//                    ((BLinearLayout) recycleView.getChildAt(0).findViewById(R.id.l_bz)).setPercent(p);
//                }
//
//                parallax.setTranslationY(mOffset - mScrollY);

            }

            @Override
            public void onFooterMoving(RefreshFooter footer, boolean isDragging, float percent, int offset, int footerHeight, int maxDragHeight) {

//                if(mScrollY==0)
//                parallax.setTranslationY(-offset - mScrollY);

            }
            //            @Override
//            public void onHeaderPulling(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
//            @Override
//            public void onHeaderReleasing(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
        });
        refreshLayout.setEnableAutoLoadMore(false);
        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                staggeredGridLayoutManager.invalidateSpanAssignments();
                staggeredGridLayoutManager.invalidateSpanAssignments();
//                int[] first = new int[2];
//                staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(first);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
//                    staggeredGridLayoutManager.invalidateSpanAssignments();
//                }

        }


            private int lastScrollY = 0;
            private int h = ScreenUtil.dp2px(Person1Activity.this, 44)+ImmersionBar.getStatusBarHeight(Person1Activity.this);


            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);




               int lastScrollY1 = recyclerView.computeVerticalScrollOffset(); //lastScrollY + dy;
//                if(dy>0&&(lastScrollY>lastScrollY1)){
//                    lastScrollY = h;
//                }else {
//                    lastScrollY = lastScrollY1;
//                }
                lastScrollY = lastScrollY1;
                Log.e("as",lastScrollY+"");
                if(lastScrollY<0){
                    lastScrollY = 0;
                }
                if (lastScrollY < h) {
                    int scrollY = Math.min(h, lastScrollY);
                    mScrollY = scrollY > h ? h : scrollY;
//                    buttonBar.setAlpha(1f * mScrollY / h);

//                    parallax.setTranslationY(mOffset - mScrollY);
                }

                if(!(lastScrollY<h)){
                    lNav.getBackground().setAlpha(255);
                    tvTitle.setVisibility(View.VISIBLE);
                }else {
                    lNav.getBackground().setAlpha(0);
                    tvTitle.setVisibility(View.INVISIBLE);
                }


            }
        });
//        recycleView.setOnScrollChangeListener(new RecyclerView.OnScrollChangeListener() {
//            private int lastScrollY = 0;
//            private int h = ScreenUtil.dp2px(PersonActivity.this,170);
//            @Override
//            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//
//
//
//                if (lastScrollY < h) {
//                    scrollY = Math.min(h, scrollY);
//                    mScrollY = scrollY > h ? h : scrollY;
////                    buttonBar.setAlpha(1f * mScrollY / h);
//
//                    parallax.setTranslationY(mOffset - mScrollY);
//                }
//                lastScrollY = scrollY;
//            }
//
//
////            private int color = ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary)&0x00ffffff;
//
//        });

        viewModel.updateUserinfo.observe(this,res->{


//            personalAdapter.notifyDataChanged();
//
//           updateIcon();
        });

        personalAdapter.personListener = new PersonAdapter1.personListener() {
            @Override
            public void praiseClick(int childPosition) {

                selectIndex =childPosition;
                CommentParam param1 = new CommentParam();
                param1.worksid = personalAdapter.data.get(childPosition).getWorksid();
                addSubscription(viewModel.addworkspraise(param1,selectIndex));
            }
        };
        viewModel.categorys.observe(this,res->{

            if(res==null)
                return;;
            categorys = res;
            personalAdapter.tag.clear();
            for (CategoryBean categoryBean : res){

                personalAdapter.tag.add(categoryBean.getWorkscategoryname());
            }
            if(res.size()>9){

                personalAdapter.tag = new ArrayList<>(personalAdapter.tag.subList(0,9)) ;
                personalAdapter.tag.add("+");

            }else {
                personalAdapter.tag.add("+");
            }

            personalAdapter.categorys=res;
            personalAdapter.notifyDataChanged();

        });
        tvTitle.setText(App.getInstance().getAccount().getUsernickname());

        personalAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder, int groupPosition, int childPosition) {

                if(personalAdapter.data.size()>0) {
                    Bundle param  = new Bundle();
                    Gson gson =new Gson();
                    param.putString("param", gson.toJson(personalAdapter.data.get(childPosition)));

                    ActivityUtil.startActivity(Person1Activity.this,OpusDetailActivity.class,param);
                }

            }
        });

        viewModel.workError.observe(this,error->{
            if(error){
                headerFreshEnd();
            }else {
                pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)-1)+"";
                footerFreshEnd();
            }
        });



        viewModel.work.observe(this,data->{

            if(data.isHeader){

                personalAdapter.data.clear();
                personalAdapter.data.addAll(data.getResult());

                headerFreshEnd();
            }else
            {
                personalAdapter.data.addAll(data.getResult());
                if(data.getResult().size()>0){
                    footerFreshEnd();
                }else
                {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }


//            if(personalAdapter.data.size()>0){
//                GroupedGridLayoutManager gridLayoutManager = new GroupedGridLayoutManager(this, 2, personalAdapter);
//                recycleView.setLayoutManager(gridLayoutManager);
//            }else {
//                recycleView.setLayoutManager(new LinearLayoutManager(this));
//            }



            personalAdapter.notifyDataChanged();



        });

        viewModel.praisePosition.observe(this,res->{
            MessageEvent messageEvent=  new MessageEvent(MessageEvent.MESSAGE_EVENT_WORK_PRAISE);
            messageEvent.worksId = personalAdapter.data.get(res).getWorksid();
            messageEvent.praiseNum = viewModel.praise.getValue();
            EventBus.getDefault().post(messageEvent);

        });

        headerFreshing();
        updateIcon();
    }


    @OnClick({R.id.iv_back, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_right:
                ActivityUtil.startActivity(this, OpusPostActivity.class);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);


                    ArrayList<String> arrayList = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia media = selectList.get(i);
                        String path = media.getCompressPath();

                        arrayList.add(path);

                    }

                    viewModel.uplaodImages(arrayList, new LoginVM.ImageResult() {
                        @Override
                        public void result(ArrayList<String> result,ArrayList<String> origin) {
                            if(result.size()==0)
                                return;

                            imgurl = result.get(0);

                            UpdateUserParam param = new UpdateUserParam();
                            UserBean userBean = App.getInstance().getAccount();
                            param.usericon =imgurl;
                            param.usernickname  =userBean.getUsernickname();
                            param.userbirthday  =userBean.getUserbirthday();
                            param.userprovince  =userBean.getUserprovince();
                            param.userrealname = userBean.getUserrealname();
                            param.usercity  =userBean.getUsercity();
                            param.usersex  =userBean.getUsersex();
                            param.userbrief  =userBean.getUserbrief();
                            param.userrank = userBean.getUserrank();
                            param.useremail = userBean.getUseremail();
                            param.useraddress = userBean.getUseraddress();
                            param.usercompany = userBean.getUsercompany();
                            param.usertel = userBean.getUsertel();
                            param.userbackground  =userBean.getUserbackground();
                            param.userfacecertificated = userBean.getUserfacecertificated();
                            addSubscription(viewModel.updateUserinfo(param));
                        }
                    },"usericon");
//                    picture.reload();

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }

    @Override
    public void onMessageEvent(MessageEvent event) {
        super.onMessageEvent(event);
        if(event.getMessage() == MessageEvent.MESSAGE_EVENT_UPDATE_USER){

            personalAdapter.notifyDataChanged();

          tvTitle.setText(App.getInstance().getAccount().getUsernickname());

            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksuserid().equals(App.getInstance().getAccount().getUserid())){
                    personalAdapter.data.get(i).setUsernickname(App.getInstance().getAccount().getUsernickname());
                }
            }
          updateIcon();

        }else  if(event.getMessage() == MessageEvent.MESSAGE_EVENT_ADD_WORKS||event.getMessage() == MessageEvent.MESSAGE_EVENT_CATEGORY_UPDATE){


            headerFreshing();

        }
        else  if(event.getMessage() == MessageEvent.MESSAGE_EVENT_DELETE_WORKS){


            boolean flag =false;
            int index=0;
            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(event.worksId)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                personalAdapter.data.remove(index);


                personalAdapter.notifyDataChanged();

               int lastScrollY = recycleView.computeVerticalScrollOffset(); //lastScrollY + dy;
                 int h = ScreenUtil.dp2px(Person1Activity.this, 44)+ImmersionBar.getStatusBarHeight(Person1Activity.this);
                if(lastScrollY<0){
                    lastScrollY = 0;
                }
                if (lastScrollY < h) {
                    int scrollY = Math.min(h, lastScrollY);
                    mScrollY = scrollY > h ? h : scrollY;
//                    buttonBar.setAlpha(1f * mScrollY / h);

//                    parallax.setTranslationY(mOffset - mScrollY);
                }

                if(!(lastScrollY<h)){
                    lNav.getBackground().setAlpha(255);
                    tvTitle.setVisibility(View.VISIBLE);
                }else {
                    lNav.getBackground().setAlpha(0);
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            }


        }
        else if(event.getMessage()==MessageEvent.MESSAGE_EVENT_UPDATE_WORKS){
            boolean flag =false;
            int index=0;

            Gson gson  = new Gson();
            AddWorkParam addWorkParam = gson.fromJson(event.addwork, AddWorkParam.class);
            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(addWorkParam.worksid)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
               OpusBean data=   personalAdapter.data.get(index);
                data.setWorkstitle(addWorkParam.title);
                data.setWorkscontent(addWorkParam.content);
                data.setWorkstags(addWorkParam.tags);
                data.setWorkspics(addWorkParam.pics);
                data.setWorkssizes(addWorkParam.sizes);




                personalAdapter.notifyDataChanged();

                int lastScrollY = recycleView.computeVerticalScrollOffset(); //lastScrollY + dy;
                 int h = ScreenUtil.dp2px(Person1Activity.this, 44)+ImmersionBar.getStatusBarHeight(Person1Activity.this);
                if(lastScrollY<0){
                    lastScrollY = 0;
                }
                if (lastScrollY < h) {

//                    buttonBar.setAlpha(1f * mScrollY / h);

//                    parallax.setTranslationY(mOffset - mScrollY);
                }

                if(!(lastScrollY<h)){
                    lNav.getBackground().setAlpha(255);
                    tvTitle.setVisibility(View.VISIBLE);
                }else {
                    lNav.getBackground().setAlpha(0);
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            }
        }
        else if(event.getMessage()==MessageEvent.MESSAGE_EVENT_WORK_PRAISE){
            boolean flag =false;
            int index=0;


            for (int i=0;i<personalAdapter.data.size();i++){

                if(personalAdapter.data.get(i).getWorksid().equals(event.worksId)){
                    flag=true;
                    index =i;
                    break;
                }
            }
            if(flag){
                OpusBean data=   personalAdapter.data.get(index);

                data.setWorkifpraise(event.praiseNum);
                if(event.praiseNum.equals("1")){
                    data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())+1)+"" );
                }else {
                    data.setWorkspraisenum((Integer.valueOf(data.getWorkspraisenum())-1)+"" );
                }




                personalAdapter.notifyChildChanged(0,index);


            }
        }
    }


    protected void headerFreshing() {
        pageParam.pagenum ="1";
        refreshLayout.resetNoMoreData();
        addSubscription(viewModel.getWork(pageParam,true));

        addSubscription(viewModel.getCategory(new UserParam()));
    }


    protected void footerFreshing() {
        pageParam.pagenum = (Integer.valueOf(pageParam.pagenum)+1)+"";

        addSubscription(viewModel.getWork(pageParam,false));
    }


    protected void headerFresh() {
        refreshLayout.autoRefresh();

    }

    protected void footerFresh() {
        refreshLayout.autoLoadMore();
    }

    protected void headerFreshEnd() {
        refreshLayout.finishRefresh();

    }

    protected void footerFreshEnd() {
        refreshLayout.finishLoadMore();
    }


}
